package com.ayitubie.refuelweb.config.aspect;
import com.ayitubie.refuelweb.config.ipUtils.IpUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Objects;

@Component
@Aspect
public class OptLogAspect {
    /**
     * 定义切点
     */
    @Pointcut("@annotation(com.ayitubie.refuelweb.config.annotation.OptLog)")
    public void optLogPointCut() {}

    @Before("optLogPointCut()")
    public void beforeAop(){
        System.out.println("前置通知...");
    }
    @After("optLogPointCut()")
    public void afterAop(){
        System.out.println("后置通知...");
    }
    @Around("optLogPointCut()")
    public Object aroundAop(ProceedingJoinPoint pj) throws Throwable {
        System.out.println("环绕通知前...");
        Object obj = pj.proceed();//需要返回结果
        System.out.println("环绕通知后...");
        return obj;
    }

    /**
     * 登录时候获取客户端信息
     * @param joinPoint 切入点
     * @param result 返回结果
     */
    @AfterReturning(value="optLogPointCut()",returning="result")
    public void saveOptLog(JoinPoint joinPoint,Object result) {
        System.out.println("后置返回值...");
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) Objects.requireNonNull(requestAttributes).resolveReference(RequestAttributes.REFERENCE_REQUEST);
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();

        Method method = signature.getMethod();
        String methodName = method.getName();
        String ipAddress = IpUtils.getIpAddress(request);
        UserAgent userAgent = IpUtils.getUserAgent(request);
        String os = userAgent.getOperatingSystem().getName();
        String browser = userAgent.getBrowser().getName();
        String ipSource = IpUtils.getIpSource(ipAddress);
        System.out.println("ipSource = " + ipSource);
        System.out.println("操作系统："+os);
        System.out.println("浏览器："+browser);
        System.out.println("请求IP："+ipAddress);
        System.out.println("方法名："+methodName);
    }


}

